const path = require('path')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
// const purgecss = require('@fullhuman/postcss-purgecss')
const cdnInfo = require('./src/dev-core/constant/cdnLoad')
const CompressionPlugin = require("compression-webpack-plugin")
const productionGzipExtensions = ['js', 'css']
// const SpritesmithPlugin = require('webpack-spritesmith')
// const PrerenderSPAPlugin = require('prerender-spa-plugin')
// const Renderer = PrerenderSPAPlugin.PuppeteerRenderer

const resolve = (dir) => {   
	return path.join(__dirname,dir)
}
const templateFunction = function(data) {
  var shared = ".iconsprite { display: inline-block; vertical-align: middle; background-image: url(I) }".replace(
    "I",
    data.sprites[0].image
  )

  var perSprite = data.sprites
    .map(function(sprite) {
      return ".iconsprite-N { width: Wpx; height: Hpx; background-position: Xpx Ypx; }"
        .replace("N", sprite.name)
        .replace("W", sprite.width)
        .replace("H", sprite.height)
        .replace("X", sprite.offset_x)
        .replace("Y", sprite.offset_y)
    })
    .join("\n")

  return shared + "\n" + perSprite
}

module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? './' : './',
  outputDir: 'bigscreen',
  assetsDir: 'static',
  indexPath: 'bigscreen.html',
  lintOnSave: process.env.NODE_ENV !== 'production',
  productionSourceMap: false,
  filenameHashing: true,
  configureWebpack: config => {
    config.externals = cdnInfo.externals
    if (process.env.NODE_ENV === 'production') {
      const plugins = []
      plugins.push(
        new UglifyJsPlugin({ 
          uglifyOptions: {
            compress: {
              drop_console: true,
              drop_debugger: false,
              pure_funcs: ['console.log']
            }
          },
          sourceMap: false,
          parallel: true
        })
      )
      plugins.push(
        new CompressionPlugin({
          filename: '[path].gz',
          algorithm: 'gzip',
          test: new RegExp(
            '\\.(' +
            productionGzipExtensions.join('|') +
            ')$'
          ),
          threshold: 10240,
          minRatio: 0.8
        })
      )
      // plugins.push(
      //   new PrerenderSPAPlugin({      
      //     staticDir: path.join(__dirname, './waterfllDrag'),
      //     routes: ['/', '/dragfile', '/testpage'],
      //     renderer: new Renderer({
      //         inject: {
      //             title: "preview"
      //         },
      //         headless: false,
      //         renderAfterDocumentEvent: 'render-event'
      //     })
      //   })
      // )
      

      config.plugins = [
        ...config.plugins,
        ...plugins
      ]
    } else {
      // config.plugins.push(
        // new SpritesmithPlugin({
        //   src: {
        //     cwd: path.resolve(__dirname, "./src/dev-core/assets/icon"),
        //     glob: "*.png"
        //   },
        //   target: {
        //     image: path.resolve(__dirname, "./src/dev-core/assets/iconsprite/sprite.png"),
        //     css: [
        //       [
        //         path.resolve(__dirname, "./src/dev-core/assets/iconcss/my_sprite.css"),
        //         {
        //           format: "function_based_template"
        //         }
        //       ]
        //     ]
        //   },
        //   apiOptions: { 
        //     cssImageRef: "../iconsprite/sprite.png"
        //   },
        //   customTemplates: {
        //     function_based_template: templateFunction
        //   },
        //   spritesmithOptions: {
        //     padding: 20 
        //   }
        // })
      // )
    }
} ,
  chainWebpack: config => {
    if (process.env.NODE_ENV === 'production') { 
      config.plugin('webpack-bundle-analyzer')
        .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
        
      // config.module
      //   .rule('images')
      //   .use('image-webpack-loader')
      //   .loader('image-webpack-loader')
      //   .options({
      //     mozjpeg: { progressive: true, quality: 65 },
      //     optipng: { enabled: false },
      //     pngquant: { quality: [0.5, 0.6], speed: 4 },
      //     gifsicle: { interlaced: false },
      //     webp: { quality: 75 }
      //   })
    }
    config.resolve.alias
      .set('@',resolve('src'))
      .set('@base',resolve('src/dev-base'))
      .set('@core',resolve('src/dev-core'))
      .set('@screen',resolve('src/dev-bigscreen'))

    config.plugin('html').tap(args => {
      if (process.env.NODE_ENV === 'production') {
        args[0].cdn = cdnInfo.cdn.build
        args[0].title = '宝能园区数据大屏'
      }
      if (process.env.NODE_ENV === 'development') {
        args[0].cdn = cdnInfo.cdn.dev
        args[0].title = '宝能园区数据大屏'
      }
      return args
    })
  },
  css: {
    requireModuleExtension: true,
    extract: process.env.NODE_ENV === 'production',
    sourceMap: false,
/*     loaderOptions: {
      sass: {
        data: '@import "src/dev-base/style/base.scss";'
      }
    }, */
    loaderOptions: { 
      postcss: {
        plugins: [
          // require('postcss-px2rem')({
          //   remUnit: 75
          // }),
    //       purgecss(
    //         {
    //           content: [`./public/**/*.html`, `./src/**/*.vue`],
    //           defaultExtractor(content) {
    //             const contentWithoutStyleBlocks = content.replace(/<style[^]+?<\/style>/gi, '')
    //             return contentWithoutStyleBlocks.match(/[A-Za-z0-9-_/:]*[A-Za-z0-9-_/]+/g) || []
    //           },
    //           safelist: [/-(leave|enter|appear)(|-(to|from|active))$/, /^(?!(|.*?:)cursor-move).+-move$/, /^router-link(|-exact)-active$/, /data-v-.*/] // 不被删除的选择器列表
    //         }
    //       )
        ]
      }
    }
  },
  devServer: {
    proxy: {
      '/maps': {
        target: 'http://wwww.maps131.com:3030',
        changeOrigin: true
      }
    },
    hot: false,
    host: '0.0.0.0',
    port: 7777,
    https: false,
    open: true
  },
  /* parallel: require('os').cpus().length > 1, */
  // pluginOptions: {
  //   'style-resources-loader': {
  //     preProcessor: 'less',
  //     patterns: [path.resolve(__dirname, "src/dev-base/style/baseless.less")]
  //   }
  // }
}